﻿using ExaminationWeb.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Exam.BLL;
using System.Security.Cryptography;
using System.Text;
using Exam.Model;
namespace ExaminationWeb.Controllers
{
    public class AccountController : Controller
    {
        UserInfoService userinfoService = new UserInfoService();
        //
        // GET: /Account/
        [AllowAnonymous]
        public ActionResult Login()
        {
            return View();
        }
        [AllowAnonymous]
        public ActionResult CustomsLogin(string CodeID, string Password, string hidusertype)
        {
            //域验证
            string DomainCheck = System.Configuration.ConfigurationManager.AppSettings["DomainCheck"].ToString();
            string Domain = System.Configuration.ConfigurationManager.AppSettings["Domain"].ToString();
            if (DomainCheck == "1")
            {   //域登录验证
                LdapAuthentication ldap = new LdapAuthentication("LDAP://" + Domain + "");
                bool isAuthenticated = ldap.IsAuthenticated(Domain, CodeID, Password);

                if (isAuthenticated)
                {
                    //  Session.Timeout = RememberMe != "on" ? int.Parse(System.Configuration.ConfigurationManager.AppSettings["sessionTimeOut"].ToString()) : int.Parse(System.Configuration.ConfigurationManager.AppSettings["sessionTimeOutRenemberMe"].ToString());
                    UserInfo user = userinfoService.LoadEntites(e => e.Code1ID == CodeID).FirstOrDefault();
                    if (user == null)
                    {
                        ViewData["LoginResult"] = "err";
                        return View("Index");
                    }
                    user.Password = Password;
                    //  user.RememberMe = RememberMe;

                    Session[WebConstants.UserIDSession] = user.UserID.ToString();
                    Session[WebConstants.UserSession] = user;
                    UserAccount.UserID = user.UserID;
                    //                    List<Role> listUserRoles = commonService.GetEntities<Role>(@"select r.* from User_Role ur
                    //                                                            left join Role r on r.RoleID=ur.RoleID
                    //                                                            where ur.UserID='" + user.UserID + "'");
                    //                    Session["LoginUserRoles"] = listUserRoles;
                    //                    List<Page> LoginUserRolePages = commonService.GetEntities<Page>(@"select p.* from Page p 
                    //                                                            left join Role_Page rp on p.PageID=rp.PageID
                    //                                                            left join User_Role ur on ur.RoleID=rp.RoleID
                    //                                                            where ur.UserID='" + user.UserID + @"'");
                    //                    Session["LoginUserRolePages"] = LoginUserRolePages;
                    //                    ViewData["LoginUserEName"] = user.EName;
                    //      ViewData["LoginUserRoles"] = listUserRoles;
                    string fromurl = Request.UrlReferrer.Query;
                    if (fromurl.IndexOf("?fromurl=") > -1)
                    {
                        fromurl = fromurl.Substring(9);
                        fromurl = VerifyTool.Decode(fromurl, "Wicresoft");
                        return this.Redirect(fromurl);
                    }
                    else
                    {
                        return this.Redirect("/Account/Home");
                    }
                }
                else
                {
                    ViewData["LoginResult"] = "errDomainCheck";
                    return View("Index");
                }
            }
            else
            {//密码登录验证
                Exam.Model.UserInfo userinfo = userinfoService.LoadEntites(e => e.Code1ID == CodeID && e.UserType == int.Parse(hidusertype) && e.Password == MD5Encrypt(Password)).FirstOrDefault();

                if (userinfo != null)
                {
                    Session.Timeout = 60;
                    Session[WebConstants.UserIDSession] = userinfo.UserID.ToString();

                    Session[WebConstants.UserSession] = userinfo;
                    UserAccount.UserID = userinfo.UserID;
                    string fromurl = Request.UrlReferrer.Query;

                    if (fromurl.IndexOf("?fromurl=") > -1)
                    {
                        fromurl = fromurl.Substring(9);
                        fromurl = VerifyTool.Decode(fromurl, "Wicresoft");
                        return this.Redirect(fromurl);
                    }
                    else
                    {
                        return this.Redirect("/Account/Home");
                    }
                }
                else
                {
                    ViewData["LoginResult"] = "err";
                    return View("Login");
                }
            }
        }
        [AllowAnonymous]
        public ActionResult Home()
        {
            return View();
        }

        public ActionResult MenuList()
        {
            Exam.Model.UserInfo userinfo = (Exam.Model.UserInfo)Session[WebConstants.UserSession];
            ViewData["UserInfo"] = userinfo;
            return View();
        }
        ///   <summary>
        ///   给一个字符串进行MD5加密
        ///   </summary>
        ///   <param   name="strText">待加密字符串</param>
        ///   <returns>加密后的字符串</returns>
        public static string MD5Encrypt(string strText)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(strText)), 4, 8);
            t2 = t2.Replace("-", "");
            return t2;
        }

        [HttpPost]
        public string LoginOut()
        {
            Session.Clear();
            return "suc";
        }
    }
}
